package com.zhz.mall.admin.config;

import com.zhz.mall.common.util.ObjectMapperUtil;
import com.zhz.mall.admin.properties.RedisConfigProperties;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.config.MasterSlaveServersConfig;
import org.redisson.config.ReadMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @description: redisson配置
 * @motto: 代码源于生活，高于生活艺术
 * @author: zhouhengzhe
 * @date: 2023/1/12 17:20
 * @since 1.0
 **/
@Configuration
public class BaseRedissonConfig {
    private static final String URL_PREFIX = "redis://";

    private static final String URL_SPLIT = ":";

    @Autowired
    private RedisConfigProperties redisConfigProperties;

    /**
     * 注册RedissonClient对象
     *
     * @return
     * @throws IOException
     */
    @Bean(destroyMethod = "shutdown")
    RedissonClient redisson() throws IOException {
        Config config = new Config();
        // watch dog 轮询时间 默认30秒
        // 如果在业务过程中 redis主节点宕机 PS: 实例切换 锁同步问题？
        // 如果业务实例宕机 锁未释放 他将在10秒之后自动释放
        config.setLockWatchdogTimeout(10 * 1000);
        // redisson 默认编码规则 jackson 使用 YGPObjectMapper
        config.setCodec(new JsonJacksonCodec(ObjectMapperUtil.getObjectMapper()));
        //主从模式
        MasterSlaveServersConfig serversConfig = config.useMasterSlaveServers().setReadMode(ReadMode.MASTER);
        //ip:port
        String address = String.join("", URL_PREFIX, redisConfigProperties.getHost(), URL_SPLIT, redisConfigProperties.getPort());
        serversConfig.setMasterAddress(address);
        serversConfig.setPassword(redisConfigProperties.getPassword());
        serversConfig.setMasterConnectionMinimumIdleSize(40);
        serversConfig.setSlaveConnectionMinimumIdleSize(25);
        return Redisson.create(config);
    }
}
